package jnpf.service.impl;

import jnpf.entity.*;
import jnpf.mapper.MzProjectcontentMapper;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.util.RandomUtil;

import java.math.BigDecimal;

import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;

import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;


import jnpf.permission.service.AuthorizeService;


import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;

import java.util.stream.Collectors;

import jnpf.model.mzprojectcontent.*;


import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.text.SimpleDateFormat;

import jnpf.util.*;

import java.util.*;

import jnpf.base.model.filter.RuleInfo;
import jnpf.util.GenUtil;

/**
 * mzProjectcontent
 * 版本： V3.2.0
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2023-12-10
 */
@Service
public class MzProjectcontentServiceImpl extends ServiceImpl<MzProjectcontentMapper, MzProjectcontentEntity> implements MzProjectcontentService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Autowired
    private MzCompilationprojectService mzCompilationprojectService;


    @Override
    public List<MzProjectcontentEntity> getList(MzProjectcontentPagination mzProjectcontentPagination) {
        return getTypeList(mzProjectcontentPagination, mzProjectcontentPagination.getDataType());
    }

    @Override
    public List<MzProjectcontentEntity> getTypeList(MzProjectcontentPagination mzProjectcontentPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int mzProjectcontentNum = 0;
        QueryWrapper<MzProjectcontentEntity> mzProjectcontentQueryWrapper = new QueryWrapper<>();
        int mzCompilationprojectNum = 0;
        QueryWrapper<MzCompilationprojectEntity> mzCompilationprojectQueryWrapper = new QueryWrapper<>();

//树形，异步父级查询条件
        long mzCompilationprojectcount = mzCompilationprojectService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(mzProjectcontentPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(mzProjectcontentPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int mzProjectcontentNum1 = 0;
            QueryWrapper<MzProjectcontentEntity> mzProjectcontentSuperWrapper = new QueryWrapper<>();
            mzProjectcontentNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(mzProjectcontentSuperWrapper, superQueryList, matchLogic, "mz_projectcontent")
                    , new MzProjectcontentEntity(), mzProjectcontentNum1);
            if (mzProjectcontentNum1 > 0) {
                List<String> mzProjectcontentList = this.list(mzProjectcontentSuperWrapper).stream().map(MzProjectcontentEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(mzProjectcontentList);
                intersectionSuperList.add(mzProjectcontentList);
            }
            int mzCompilationprojectNum1 = 0;
            QueryWrapper<MzCompilationprojectEntity> mzCompilationprojectSuperWrapper = new QueryWrapper<>();
            mzCompilationprojectNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(mzCompilationprojectSuperWrapper, superQueryList, matchLogic, "mz_compilationproject")
                    , new MzCompilationprojectEntity(), mzCompilationprojectNum1);
            if (mzCompilationprojectNum1 > 0 && mzCompilationprojectcount > 0) {

                List<String> mzCompilationprojectList = mzCompilationprojectService.list(mzCompilationprojectSuperWrapper).stream().map(MzCompilationprojectEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(mzCompilationprojectList);
                intersectionSuperList.add(mzCompilationprojectList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object mzProjectcontentObj = authorizeService.getCondition(new AuthorizeConditionModel(mzProjectcontentQueryWrapper, mzProjectcontentPagination.getMenuId(), "mz_projectcontent"));
                if (ObjectUtil.isEmpty(mzProjectcontentObj)) {
                    return new ArrayList<>();
                } else {
                    mzProjectcontentQueryWrapper = (QueryWrapper<MzProjectcontentEntity>) mzProjectcontentObj;
                    if (mzProjectcontentQueryWrapper.getExpression().getNormal().size() > 0) {
                        mzProjectcontentNum++;
                    }
                }
                Object mzCompilationprojectObj = authorizeService.getCondition(new AuthorizeConditionModel(mzCompilationprojectQueryWrapper, mzProjectcontentPagination.getMenuId(), "mz_compilationproject"));
                if (ObjectUtil.isEmpty(mzCompilationprojectObj)) {
                    return new ArrayList<>();
                } else {
                    mzCompilationprojectQueryWrapper = (QueryWrapper<MzCompilationprojectEntity>) mzCompilationprojectObj;
                    if (mzCompilationprojectQueryWrapper.getExpression().getNormal().size() > 0) {
                        mzCompilationprojectNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object mzProjectcontentObj = authorizeService.getCondition(new AuthorizeConditionModel(mzProjectcontentQueryWrapper, mzProjectcontentPagination.getMenuId(), "mz_projectcontent"));
                if (ObjectUtil.isEmpty(mzProjectcontentObj)) {
                    return new ArrayList<>();
                } else {
                    mzProjectcontentQueryWrapper = (QueryWrapper<MzProjectcontentEntity>) mzProjectcontentObj;
                    if (mzProjectcontentQueryWrapper.getExpression().getNormal().size() > 0) {
                        mzProjectcontentNum++;
                    }
                }


                Object mzCompilationprojectObj = authorizeService.getCondition(new AuthorizeConditionModel(mzCompilationprojectQueryWrapper, mzProjectcontentPagination.getMenuId(), "mz_compilationproject"));
                if (ObjectUtil.isEmpty(mzCompilationprojectObj)) {
                    return new ArrayList<>();
                } else {
                    mzCompilationprojectQueryWrapper = (QueryWrapper<MzCompilationprojectEntity>) mzCompilationprojectObj;
                    if (mzCompilationprojectQueryWrapper.getExpression().getNormal().size() > 0) {
                        mzCompilationprojectNum++;
                    }
                }


            }
        }


        if (isPc) {
            if (ObjectUtil.isNotEmpty(mzProjectcontentPagination.getJnpf_mz_compilationproject_jnpf_projectname())) {
                mzCompilationprojectNum++;

                mzCompilationprojectQueryWrapper.lambda().like(MzCompilationprojectEntity::getProjectname, mzProjectcontentPagination.getJnpf_mz_compilationproject_jnpf_projectname());

            }

            if (ObjectUtil.isNotEmpty(mzProjectcontentPagination.getTitle())) {
                mzProjectcontentNum++;

                mzProjectcontentQueryWrapper.lambda().like(MzProjectcontentEntity::getTitle, mzProjectcontentPagination.getTitle());

            }

            if (ObjectUtil.isNotEmpty(mzProjectcontentPagination.getCompilationtypeid())) {
                mzProjectcontentNum++;

                mzProjectcontentQueryWrapper.lambda().like(MzProjectcontentEntity::getCompilationtypeid, mzProjectcontentPagination.getCompilationtypeid());

            }
            if (ObjectUtil.isNotEmpty(mzProjectcontentPagination.getCompilationProjectId())) {
                mzProjectcontentNum++;

                mzProjectcontentQueryWrapper.lambda().like(MzProjectcontentEntity::getCompilationprojectid, mzProjectcontentPagination.getCompilationProjectId());

            }

        }
        if (mzCompilationprojectNum > 0) {
            List<String> mzCompilationprojectIdList = mzCompilationprojectService.list(mzCompilationprojectQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getId())).map(t -> t.getId()).collect(Collectors.toList());
            long count = mzCompilationprojectService.count();
            if (count > 0) {
                intersectionList.add(mzCompilationprojectIdList);
            }
            AllIdList.addAll(mzCompilationprojectIdList);
        }
        total += mzCompilationprojectNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            mzProjectcontentQueryWrapper.lambda().in(MzProjectcontentEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            mzProjectcontentQueryWrapper.lambda().and(t -> t.in(MzProjectcontentEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(mzProjectcontentPagination.getSidx())) {
            mzProjectcontentQueryWrapper.lambda().orderByDesc(MzProjectcontentEntity::getId);
        } else {
            try {
                String sidx = mzProjectcontentPagination.getSidx();
                MzProjectcontentEntity mzProjectcontentEntity = new MzProjectcontentEntity();
                Field declaredField = mzProjectcontentEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                mzProjectcontentQueryWrapper = "asc".equals(mzProjectcontentPagination.getSort().toLowerCase()) ? mzProjectcontentQueryWrapper.orderByAsc(value) : mzProjectcontentQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<MzProjectcontentEntity> page = new Page<>(mzProjectcontentPagination.getCurrentPage(), mzProjectcontentPagination.getPageSize());
                IPage<MzProjectcontentEntity> userIPage = this.page(page, mzProjectcontentQueryWrapper);
                return mzProjectcontentPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<MzProjectcontentEntity> list = new ArrayList();
                return mzProjectcontentPagination.setData(list, list.size());
            }
        } else {
            return this.list(mzProjectcontentQueryWrapper);
        }
    }

    private boolean onlyMainFilter(String moduleId) {
        List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(moduleId);
        for (RuleInfo info : ruleInfos) {
            if (info.getField().contains("_jnpf_") || info.getField().contains("-")) {
                return false;
            }
        }
        return true;
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                    if (!tableName.equals(field.split("-")[0])) {
                        continue;
                    }
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.setDbType("mysql");
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public MzProjectcontentEntity getInfo(String id) {
        QueryWrapper<MzProjectcontentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MzProjectcontentEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(MzProjectcontentEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, MzProjectcontentEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(MzProjectcontentEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法
    @Override
    public MzCompilationprojectEntity getMzCompilationproject(String id) {
        QueryWrapper<MzCompilationprojectEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MzCompilationprojectEntity::getId, id);
        return mzCompilationprojectService.getOne(queryWrapper);
    }

    //根据采编类型id查询相关采编内容
    @Override
    public List<MzProjectcontentEntity> getMzProjectcontentByTypeId(String typeId) {
        QueryWrapper<MzProjectcontentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MzProjectcontentEntity::getCompilationtypeid, typeId);
        return this.list(queryWrapper);
    }


    //验证表单唯一字段
    @Override
    public String checkForm(MzProjectcontentForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getMz_compilationproject())) {
        }

        return countRecover;
    }


}
